package com.young.shop.controller;

import com.young.shop.pojo.entity.User;
import com.young.shop.service.UserService;
import com.young.shop.service.impl.UserServiceImple;
import com.young.shop.utils.email;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/register")
public class UserRegisterController extends BaseController {
    @Override
    protected void doGet(HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入doget");
        doPost(req, resp);
    }

    private UserService userService=new UserServiceImple();
    @Override
    protected void doPost(HttpServletRequest req , HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入dopost");
        //获取参数 邮箱 密码 对应的验证码、勾选的值
        User user = convertParamsToUser(req);
        String code = req.getParameter("code");
        String checkBox = req.getParameter("check");
        try{
            //校验参数 非空、是否存在、判断验证码是否相同
            User dbUser = userService.checkRegisterParams(user,code,checkBox);
            //存到数据库
            User saveUser = userService.save(user);
            //存入session
            req.getSession().setAttribute("client",saveUser);
            writerSucccessBaseRespVoToResponse(resp,saveUser);
        }catch (RuntimeException e){
            writerFailedBaseRespVoToResponse(resp,e);
        }

    }



    private User convertParamsToUser(HttpServletRequest req) {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        return user;
    }
}
